import 'dart:async';

import 'package:FineArt/components/horizon_scroll.dart';
import 'package:FineArt/components/rounded_text_with_del.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/core/widget/grid/grid_item_photo.dart';
import 'package:FineArt/core/widget/grid/grid_item_video.dart';
import 'package:FineArt/core/widget/grid/grid_staggered_item_photo.dart';
import 'package:FineArt/page/home/book_content_grid_page.dart';
import 'package:FineArt/page/home/components/module_filter.dart';
import 'package:FineArt/page/imageview/BookPreview.dart';
import 'package:FineArt/page/imageview/ImagePreview.dart';
import 'package:FineArt/page/imageview/VideoPlayer.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class ModuleVideoPage extends StatefulWidget {
  final Module _module;

  ModuleVideoPage(this._module);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _ModuleVideoPageState(this._module);
  }
}

class _ModuleVideoPageState extends State<ModuleVideoPage> {
  final Module _module;

  EasyRefreshController _controller = EasyRefreshController();

  _ModuleVideoPageState(this._module);

  List<Category> default_categories = [];
  List<Resource> resources = [];
  int currentPage = 0;
  String currentPath = "";
  String currentFilter = "";
  int currentPid = 0;

  bool isFilter = false;
  String confirmKey;
  String currentCategoryLabel;
  Category currentCategory;

  double currentScrollOffset = 0; //for categories

  MoreFilterGroup filterGroupRoot;

  List<MoreFilterGroup> filterGroups = [];

  //获取标签目录
  void _get_default_categories() {
    LogUtil.d("_ModuleVideoPageState _get_default_categories");
    ModuleApi().categories(_module.id, _module.id).then((res) {
      if (!this.mounted) return;
      setState(() {
        default_categories.clear();
        Category all = new Category(
            label: "全部", selected: true, path: _module.id.toString(), id: 0);
        default_categories.add(all);
        default_categories.addAll(res.data);
      });
    });
  }

  void _getAll() {
    resources.clear();
    currentPage = 0;
    currentPath = _module.id.toString();
    currentFilter = "";
    currentCategoryLabel = "全部";
    _nextPage(currentPath, currentFilter);
  }

  // bool busy = false;
  // Timer _timer = null;
  String testUrl = "https://publish-cdn.sundocloud.com/static/pictures/3272.3238.3171.2/thumbnail/4e014f40b6cc4b207beb58810af7870a.jpg";
  //获取数据
  void _nextPage(String path, String filter) {
    // if (busy) return;
    // busy = true;
    LogUtil.d("_ModuleVideoPageState _nextPage");
    // LogUtil.d(StackTrace.current);
    ModuleApi().search(path, filter, currentPage, PAGE_SIZE).then((res) {
      // busy = false;
      // if (_timer != null)
      //   {
      //     _timer.cancel();
      //   }
      if (!this.mounted) return;
      setState(() {
        //这行代码很别扭，但是解决了可能是控件本身的一个bug，当不够一页数据时会重复加载两次
        if (resources.length < PAGE_SIZE && resources.length > 0) return;
        currentPage = res.data.pageIndex + 1;
        // if(res.data.list.length<10){
        //   for(int i=0;i<10;i++){
        //     resources.add(new Resource(url: testUrl,type: 6,id: i,title: "静物组合操作视频:真香多少的几211231"));
        //   }
        // }
        resources.addAll(res.data.list);
        _controller.finishLoad(success: true);
      });
    });

    // if (_timer != null)
    // {
    //   _timer.cancel();
    // }
    // _timer = Timer(new Duration(seconds: 5),(){
    //   ToastUtils.error("网络超时，请刷新重试");
    //   busy = false;
    // });

  }

  void on_categories_selected(Category category, double offset) {
    resources.clear();
    filterGroups.clear();
    currentPage = 0;
    currentPath = category.path;
    currentFilter = "";
    currentPid = category.id;
    currentCategoryLabel = category.label;
    currentCategory = category;
    currentScrollOffset = offset;
    // _nextPage(currentPath, currentFilter);
    _controller.callRefresh();
  }

  void request_with_filter(String path, String filter) {
    //String _filter = Uri.encodeComponent(filter);
    resources.clear();
    filterGroups.clear();
    currentPage = 0;
    currentPath = path;
    currentFilter = filter;
    currentPid = currentPid;
    // _nextPage(currentPath, currentFilter); //
    _controller.callRefresh();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    LogUtil.d("_ModuleVideoPageState initState");
    _getAll();
    _get_default_categories();
  }

  @override
  void didChangeDependencies() {
    LogUtil.d("module_page didChangeDependencies");
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    var width = MediaQuery.of(context).size.width * 0.88;
    return Scaffold(
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 2, horizontal: 2),
              child: Row(
                children: [
                  isFilter
                      ? RoundedTextWithDel(
                          label: confirmKey,
                          height: 30,
                          width: width,
                          press: () {
                            setState(() {
                              isFilter = false;
                            });
                            if (currentCategory != null) {
                              on_categories_selected(
                                  currentCategory, currentScrollOffset);
                            } else {
                              _getAll();
                            }
                          },
                        )
                      : MHorizontalContainer(
                          categories: this.default_categories,
                          onTapItem: this.on_categories_selected,
                          scrollOffset: this.currentScrollOffset,
                          width: width,
                          height: getPortraitSHeight(30),
                        ),
                  SizedBox(
                    width: 6,
                  ),
                  InkWell(
                    child: Image.asset(
                      "assets/images/icon_more.png",
                      // fit: BoxFit.fill,
                      width: getPortraitSWidth(16.5),
                      height: getPortraitSHeight(16.5),
                    ),
                    onTap: () {
                      print("more click>>>>>>");
                      showMoreFilter();
                    },
                  )
                ],
              ),
            ),
            SizedBox(height: getPortraitSHeight(8)),
            Expanded(child: _widget_grid()),
          ],
        ));
  }

  void showBottomModel() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        barrierColor: Colors.transparent,
        backgroundColor: Colors.white,
        elevation: 0,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(0), topRight: Radius.circular(0))),
        builder: (BuildContext context) {
          return SizedBox(
            // heightFactor: 0.88,
            height: getPortraitSHeight(550),
            child: ModuleGroupFilter(
              filterGroups: filterGroups,
              confirmPress: () => _confirmAction(),
            ),
          );
        });
  }

  void showMoreFilter() {
    LogUtil.d("video getData ${_module.section}");
    ModuleApi().moreFilters(_module.id, currentPid, currentPath).then((res) {
      if (res.code == 200) {
        setState(() {
          filterGroups.clear();
          if (res.data.group_items != null) {
            MoreFilterGroup root = res.data;
            filterGroups.add(root);
            root.level = filterGroups.length;
          }
          showBottomModel();
        });
      }
    });
  }

  Widget getEmptyWidget() {
    return Text("");
  }

  Widget _widget_grid() {
    double width = MediaQuery.of(context).size.width * 0.98;
    ScrollController _scrollController = new ScrollController();
    MaterialHeader header =
        MaterialHeader(completeDuration: new Duration(milliseconds: 100));
    return EasyRefresh.custom(
      controller: _controller,
      header: header,
      footer: MaterialFooter(),
      onRefresh: () async {
        currentPage = 0;
        resources.clear();
        _nextPage(currentPath, currentFilter);
      },
      onLoad: () async {
        _nextPage(currentPath, currentFilter);
      },
      slivers: <Widget>[
        _sliverPadding(width)
        // SliverToBoxAdapter(
        //   child: RefreshIndicator(
        //     onRefresh: () async {
        //       await Future.delayed(Duration(seconds: 5));
        //     },
        //     child: Padding(
        //       padding: const EdgeInsets.only(top: 2, left: 4, right: 4),
        //       child: _getGridBuilder(_scrollController),
        //     ),
        //     // (index) => new StaggeredTile.count(2, index==0?2.5:3)),
        //   ),
        // ),
      ],
    );
  }
  _sliverPadding(width){
   return SliverPadding(
        padding: EdgeInsets.only(left: 3, right: 3),
        sliver: SliverGrid(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            mainAxisSpacing: 3,
            crossAxisSpacing: 3,
            childAspectRatio: 1.35,
          ),
          delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index) {
              //创建子widget
              var resource = resources[index];
              return GridItemVideo(
                  url: resource.url,
                  width: width / 2,
                  height: width /2*0.6,
                  title: resource.title,
                  serious: resource.series,
                  boxFit: BoxFit.fill,
                  onTap: () {
                    // ToastUtils.toast('${resource.url}/${resource.id}');
                    // ImageViewPage.JumpToImagePreview(resource, context);
                    VideoPlayer.JumpToVideoView(resource, context);
                  });
            },
            childCount: resources.length,
          ),
        ));
  }
  resetAction() {
    setState(() {
      if (filterGroups.length > 0) {
        int c = filterGroups.length - 1;
        for (int i = 0; i < c; i++) {
          filterGroups.removeLast();
        }

        MoreFilterGroup g = filterGroups.first;
        for (int i = 0; i < g.group_items.length; i++) {
          g.group_items[i].selected = false;
        }
      }
    });
  }

  _confirmAction() {
    if (filterGroups.length > 0) {
      String path = "";
      String filter = "";
      String label = "";
      for (int i = filterGroups.length - 1; i >= 0; i--) {
        MoreFilterGroup mfg = filterGroups[i];
        if (mfg.asFilterObject) {
          for (int j = 0; j < mfg.group_items.length; j++) {
            if (mfg.group_items[j].selected) {
              filter += mfg.group_items[j].label;
              filter += "|";
              break;
            }
          }
        } else {
          for (int j = 0; j < mfg.group_items.length; j++) {
            if (mfg.group_items[j].selected) {
              path = mfg.group_items[j].path;
              break;
            }
          }
          if (path.isNotEmpty) break;
        }
      }
      //获取选中的label
      for (int i = 0; i < filterGroups.length; i++) {
        MoreFilterGroup mfg = filterGroups[i];
        for (int j = 0; j < mfg.group_items.length; j++) {
          if (mfg.group_items[j].selected) {
            label += mfg.group_items[j].label;
            label += "-";
            break;
          }
        }
      }
      if (filter.endsWith("|")) {
        filter = filter.substring(0, filter.length - 1);
      }
      if (label.endsWith("-")) {
        label = label.substring(0, label.length - 1);
      }
      LogUtil.d("label $label");
      setState(() {
        isFilter = true;
        if (currentCategoryLabel == "全部") {
          confirmKey = label;
        } else {
          confirmKey = (currentCategoryLabel + "-" + label);
        }
      });
      request_with_filter(path, filter);

      // ToastUtils.success(path + "~" + filter);
    }

    Navigator.of(context).pop();
  }


}
